import serial

'''
import serial
①选择设备
ser=serial.Serial("/dev/ttyUSB0",9600,timeout=0.5) #使用USB连接串行口
ser=serial.Serial("/dev/ttyAMA0",9600,timeout=0.5) #使用树莓派的GPIO口连接串行口
ser=serial.Serial(1,9600,timeout=0.5)                       #winsows系统使用com1口连接串行口
ser=serial.Serial("com1",9600,timeout=0.5)              #winsows系统使用com1口连接串行口
ser=serial.Serial("/dev/ttyS1",9600,timeout=0.5)       #Linux系统使用com1口连接串行口
print ser.name        #打印设备名称
print ser.port           #打印设备名
ser.open()               #打开端口
s = ser.read(10)      #从端口读10个字节
ser.write("hello")     #向端口写数据
ser.close()               #关闭端口
data = ser.read(20) #读20个字符


data = ser.readline() #是读一行，以/n结束，要是没有/n就一直读，阻塞。

data = ser.readlines()  和  ser.xreadlines()     #都需要设置超时时间

ser.baudrate = 9600      #设置波特率

ser.isOpen()                   #看看这个串口是否已经被打开

'''


class SpcSerial:



    name = "serialX"
    port = "/dev/ttyAMA0"
    baudrate = 115200
    serial = serial.Serial()

    def __init__(self, name = "serialX",
                 port = "/dev/ttyAMA0",
                 baudrate = 115200):
        self.name = name
        self.port = port
        self.baudrate = baudrate
        print(name," ",port, " baud=",baudrate)
        self.serial = serial.Serial(port, baudrate, timeout=1)
        return

    def __del__(self):
        print(self.name," is delet\n")
        self.serial.__del__()
        return

    def Open(self):
        if self.serial.isOpen():
            pass
        else:
            self.serial.open()

        print(self.name," is open\n")
        return

    def Close(self):
        if self.serial.isOpen():
            self.serial.close()
        else:
            pass
        print(self.name, " is close\n")
        return

    def Send(self,data = "__?__"):
        self.serial.write(data.encode("utf-8"))
        return

    def ReadLine(self):
        data = self.serial.readline()
        dataArray = list(data)
        datalen = len(dataArray)
        return (dataArray, datalen)



if __name__ == "__main__":

    r_data = "".encode("utf-8")
    uart = SpcSerial("serial1")
    uart.Open()
    while True:
        
        (r_data, size) = uart.ReadLine()
        print("Get {0} byte >>".format(size), end=' ')
        for d in r_data:
            print(d.hex(),end=' ')
        print("\n")
        continue
    uart.Close()
    uart.__del__()